<template>
  <div class="page">
    <div class="back">
      <div class="back-botto" @click="goback"><img src="@/assets/images/community/back.png" alt="back"></div>
    </div>
    <div class="content">
      <div class="import-img" :class="{ 'has-files': fileList.length > 0 }">
        <van-uploader
          v-model="fileList"
          multiple
          :max-count="6"
          :preview-size="100"
          :after-read="afterRead"
          @delete="deleteImg"
          class="uploader"
        />
      </div>
      <div class="input-area">
        <div class="title-wrapper">
          <input 
            type="text" 
            class="title-input" 
            placeholder="添加标题" 
            v-model="formData.title"
            maxlength="20"
          >
          <span class="title-count">{{ formData.title.length }}/20</span>
        </div>
        <div class="editor-container">
          <Editor
            v-model="formData.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
            style="height: 300px; overflow-y: hidden;"
          />
        </div>
      </div>
    </div>
    <div class="bottom-bar">
      <div class="privacy-settings">
        <div class="privacy-option" @click="togglePrivacy">
          <img :src="formData.isPublic === '1' ? publicIcon : privateIcon" alt="privacy">
          <span>{{ formData.isPublic === '1' ? '公开可见' : '私密可见' }}</span>
        </div>
      </div>
      <button class="publish-btn" @click="publish">发布笔记</button>
    </div>
  </div>
</template>

<script setup>
import { ref, shallowRef, onBeforeUnmount } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor } from '@wangeditor/editor-for-vue'
import { useRouter } from 'vue-router'
import { showToast, closeToast } from 'vant'
import { postTweet } from '../api/index'
const router = useRouter()
const fileList = ref([]);
// 删除这两行，因为已经在formData中定义了
// const title = ref('');
// const isPublic = ref(true);

//表单数据
const formData = ref({
  title: '',
  content: '',
  isPublic: '1', // 默认公开
  images: [] // 修正拼写错误，从imges改为images
});
// 引入图标
const publicIcon = new URL('@/assets/images/community/lock.png', import.meta.url).href;
const privateIcon = new URL('@/assets/images/community/lockon.png', import.meta.url).href;

const goback = () => {
  router.go(-1)
}

const editorRef = shallowRef()
const valueHtml = ref('')
const mode = ref('default')

// 编辑器配置
const editorConfig = {
  placeholder: '添加文字内容...',
  autoFocus: false,
  toolbarKeys: [], // 空数组表示不显示任何工具栏按钮
  maxLength: 200,
  MENU_CONF: {}, // 初始化菜单配置
  // 设置回车换行时的标签
  hoverbarKeys: {
    text: []
  },
  // 自定义样式
  customStyle: `
    .w-e-text-container .w-e-text {
      letter-spacing: 0 !important;
      white-space: pre !important;
      line-height: 0.8 !important;
      font-size: 14px;
    }
    .w-e-text-container .w-e-text p {
      margin: 0 !important;
      padding: 0 !important;
      line-height: 1 !important;
      min-height: auto !important;
    }
    .w-e-text-container .w-e-text br {
      display: none !important;
    }
    .w-e-text-container .w-e-text div {
      margin: 0 !important;
      padding: 0 !important;
      line-height: 1 !important;
    }
  `
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor;
  // 监听输入事件
  editor.on('change', () => {
    // 获取原始文本并去除首尾空白字符
    const text = editor.getText().trim();
    // 去除多余的空白字符和换行符
    const cleanText = text.replace(/[\r\n\s]+/g, ' ').trim();
    if (cleanText.length > 200) {
      // 保存当前光标位置
      const selection = editor.getSelection();
      // 获取原始文本
      const originalText = editor.getText();
      // 找到对应的200个有效字符的位置
      let validCount = 0;
      let cutPosition = 0;
      for (let i = 0; i < originalText.length && validCount < 200; i++) {
        if (!/[\r\n\s]/.test(originalText[i])) {
          validCount++;
        }
        cutPosition = i;
      }
      // 截取到正确位置
      editor.setText(originalText.slice(0, cutPosition + 1));
      // 恢复光标位置
      if (selection) {
        editor.select(Math.min(selection.anchor, cutPosition + 1), Math.min(selection.focus, cutPosition + 1));
      }
      // 显示友好提示
      showToast({
        message: '已达到200字上限啦~',
        type: 'warning',
        position: 'top',
        duration: 2000,
        className: 'custom-toast'
      });
    }
  });
}

const afterRead = (file) => {
  if (file.file) {
    // 创建预览URL
    file.url = URL.createObjectURL(file.file);
    
    // 获取文件路径并添加到formData
    const filePath = file.file.name;
    formData.value.images.push(filePath);
  }
};
const deleteImg = (index) => {
  fileList.value.splice(index, 1);
  formData.value.images.splice(index, 1);
}

// 添加切换私密/公开的方法
const togglePrivacy = () => {
  formData.value.isPublic = formData.value.isPublic === '1' ? '0' : '1';
};

const publish = async () => {
  console.log('fileList:', fileList.value);
  console.log('formData:', formData.value);
  
  if (!formData.value.title.trim()) {
    showToast({
      message: '请输入标题',
      type: 'warning',
      position: 'top'
    });
    return;
  }

  if (!formData.value.content.trim()) {
    showToast({
      message: '请输入内容',
      type: 'warning',
      position: 'top'
    });
    return;
  }

  // 修改内容字数检查
  const cleanContent = formData.value.content.trim().replace(/[\r\n\s]+/g, ' ').trim();
  if (cleanContent.length > 207) {
    showToast({
      message: '内容超出200字限制，请精简后发布~',
      type: 'warning',
      position: 'top',
      duration: 2000,
      className: 'custom-toast'
    });
    return;
  }

  if (fileList.value.length === 0) {
    showToast({
      message: '请至少上传一张图片',
      type: 'warning',
      position: 'top'
    });
    return;
  }

  try {
    showToast({
      type: 'loading',
      message: '发布中...',
      duration: 0
    });

    // 创建 FormData 对象来上传文件
    const submitData = new FormData();
    submitData.append('title', formData.value.title);
    submitData.append('content', formData.value.content);
    submitData.append('isPublic', formData.value.isPublic);
    
    // 添加文件到 FormData
    fileList.value.forEach((item, index) => {
      if (item.file) {
        submitData.append('images', item.file);
      }
    });

    const res = await postTweet(submitData);
    
    closeToast();
    
    if (res.data.code === 200) {
      showToast({
        type: 'success',
        message: '发布成功',
        position: 'top'
      });
      router.push('/community');
    } else {
      const errorMsg = res.data?.message || '发布失败';
      showToast({
        type: 'fail',
        message: errorMsg,
        position: 'top'
      });
    }
  } catch (err) {
    closeToast();
    console.error('发布失败:', err);
    showToast({
      type: 'fail',
      message: '发布失败，请稍后重试',
      position: 'top'
    });
  }
};
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  position: relative;

  .back {
    position: sticky;
    top: 0;
    z-index: 10;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    height: 50px;
    background-color: #fff;
    border-bottom: 1px solid #f5f5f5;
    .back-botto {
      width: 30px;
      height: 30px;
    }
  }

  .content {
    flex: 1;
    padding: 16px;
    padding-bottom: 80px;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;

    .import-img {
      margin-bottom: 20px;
      
      .uploader {
        :deep(.van-uploader__wrapper) {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 8px;
        }
        
        :deep(.van-uploader__upload) {
          width: 100px;
          height: 100px;
          margin: 0;
          background-color: #f8f8f8;
          border-radius: 4px;
        }
        
        :deep(.van-uploader__preview) {
          margin: 0;
          border-radius: 4px;
          overflow: hidden;
        }
      }
    }

    .input-area {
      .title-wrapper {
        position: relative;
        margin-bottom: 16px;
        border-bottom: 1px solid #f5f5f5;
        
        .title-input {
          width: 100%;
          padding: 12px;
          padding-right: 50px; // 为计数器留出空间
          border: none;
          font-size: 16px;
          &::placeholder {
            color: #999;
          }
        }

        .title-count {
          position: absolute;
          right: 12px;
          bottom: 12px;
          font-size: 12px;
          color: #999;
        }
      }

      .editor-container {
        margin-top: 16px;
        border: 1px solid #f5f5f5;
        border-radius: 8px;
        overflow: hidden;
        position: relative;  // 添加相对定位

        :deep(.w-e-text-container) {
          border: none;
          min-height: 300px !important;
          height: auto !important;
          max-height: none !important;

          .w-e-scroll {
            padding: 0 12px;
            min-height: 300px !important;
            height: auto !important;
          }

          // 隐藏右下角字数显示
          .w-e-text-number {
            display: none !important;
          }

          .w-e-text {
            min-height: 300px !important;
            height: auto !important;
            overflow-y: visible;
            background-color: #fff;
            padding: 12px 0;
            white-space: pre !important;
            line-height: 0.8 !important;
            font-size: 14px;

            p {
              margin: -2px 0 !important;
              padding: 0 !important;
              line-height: 0.8 !important;
              min-height: auto !important;
            }

            div {
              margin: -2px 0 !important;
              padding: 0 !important;
              line-height: 0.8 !important;
            }

            br {
              display: none !important;
            }
          }
        }
      }
    }
  }

  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    border-top: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    z-index: 100;

    .privacy-settings {
      .privacy-option {
        display: flex;
        align-items: center;
        gap: 8px;
        img {
          width: 20px;
          height: 20px;
        }
        span {
          color: #666;
          font-size: 14px;
        }
      }
    }

    .publish-btn {
      background-color: #007bff;
      color: white;
      border: none;
      padding: 8px 24px;
      border-radius: 20px;
      font-size: 14px;
      cursor: pointer;

      &:active {
        opacity: 0.9;
      }
    }
  }
}

:deep(.custom-toast) {
  background: rgba(255, 236, 217, 0.9) !important;
  color: #ff9800 !important;
  border-radius: 20px !important;
  padding: 10px 20px !important;
  font-size: 14px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}
</style>